package com.fcat.springboot.swagger.config;

import io.swagger.annotations.ApiOperation;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import springfox.documentation.builders.*;
import springfox.documentation.oas.annotations.EnableOpenApi;
import springfox.documentation.service.*;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;

@Configuration
@EnableOpenApi
public class SwaggerConfiguration implements EnvironmentAware {

	private String applicationName;

	/**
	 * swagger3的配置文件
	 */
	@Bean
	public Docket createRestApi() {
//		return new Docket(DocumentationType.OAS_30)
		return new Docket(DocumentationType.SWAGGER_2)
				// 将api的元信息设置为包含在json ResourceListing响应中。
				.apiInfo(apiInfo())
				// 选择哪些接口作为swagger的doc发布
				.select()
				.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
				.paths(PathSelectors.any())
				.build();
	}

	/**
	 * 构建 api文档的详细信息函数,注意这里的注解引用的是哪个
	 */
	private ApiInfo apiInfo() {
		// 获取工程名称
		String projectName = System.getProperty("user.dir");
		if(this.applicationName!=null && !this.applicationName.trim().isEmpty()){
			projectName = this.applicationName;
		}
		return new ApiInfoBuilder()
				.title(projectName.substring(projectName.lastIndexOf("\\") + 1) + " API接口文档")
				.contact(new Contact("liuxiangfei", "", "cissalcliu@163.com"))
				.version("1.0")
				.description("API文档")
				.build();
	}

	@Override
	public void setEnvironment(Environment environment) {
		this.applicationName = environment.getProperty("spring.application.name");
	}
}
